package com.mgee.netty.server.service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.protobuf.Any;
import com.mgee.netty.server.constant.MessagingConst;
import com.mgee.netty.server.netty.IoSession;
import com.mgee.netty.server.netty.SessionManager;
import com.mgee.netty.server.pojo.ChatUserInfo;
import com.mgee.netty.server.pojo.LobbyInfo;
import com.mgee.netty.server.pojo.LobbyRoomInfo;
import com.mgee.netty.server.protobuf.ImProto.ImMsg;
import com.mgee.netty.server.protobuf.ImProto.JoinLobbyRequest;
import com.mgee.netty.server.protobuf.ImProto.JoinLobbyRsp;
import com.mgee.netty.server.protobuf.ImProto.LeaveLobbyRsp;
import com.mgee.netty.server.protobuf.ImProto.LobbyInfoRsp;
import com.mgee.netty.server.util.MessageBuilder;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author mileswan
 *
 */
@Service
@Slf4j
public class LobbyService {
	
	@Autowired
	private SessionManager sessionManager;
	@Autowired
	private LobbyRoomService lobbyRoomService;
	
	public void JoinLobby(ImMsg imMsg, IoSession currSession) {
		
		try {
			if(currSession.getUser() == null) {
				currSession.sendMessage(MessageBuilder.buildErrorResponse(imMsg, MessagingConst.RESPONSE_ERR_CODE_400, "用户未登录!"));
				return;
			}
			String senderUid = currSession.getUser().getUid();
			JoinLobbyRequest joinLobbyRequest = imMsg.getMsg().unpack(JoinLobbyRequest.class);
			
			String lobbyName = joinLobbyRequest.getLobbyname();
			LobbyInfo lobbyInfo;
			if(!SessionManager.lobbies.containsKey(lobbyName)) {
				lobbyInfo = new LobbyInfo();
				lobbyInfo.setName(lobbyName);
				lobbyInfo.setRoomsInfo(new ConcurrentHashMap<String, LobbyRoomInfo>());
				SessionManager.lobbies.put(lobbyName, lobbyInfo);
			}else {
				lobbyInfo = SessionManager.lobbies.get(lobbyName);
			}
			
			SessionManager.userId2Lobbies.put(senderUid, lobbyInfo);
			
			Map<String, ChatUserInfo> lobbyUserMap = SessionManager.lobby2Users.get(lobbyName);
			if(lobbyUserMap == null) {
				lobbyUserMap = new ConcurrentHashMap<String, ChatUserInfo>();
			}
			ChatUserInfo userInfo = currSession.getUser();
			lobbyUserMap.put(userInfo.getUid(), userInfo);
			SessionManager.lobby2Users.put(lobbyName, lobbyUserMap);
			
			//广播大厅信息消息
			LobbyInfoRsp.Builder lobbyInfoRspBuilder = LobbyInfoRsp.newBuilder();
			lobbyInfoRspBuilder.addAllMRoomInlobby(MessageBuilder.buildRoomInfoListMsg(lobbyInfo.getRoomsInfo().values()));
			ImMsg.Builder imMsglobbyInfoBuilder = ImMsg.newBuilder();
            
			imMsglobbyInfoBuilder.setMsg(Any.pack(lobbyInfoRspBuilder.build()));
			imMsglobbyInfoBuilder.setId(imMsg.getId());
			sessionManager.sendMessageToAllLobbyUsers(imMsglobbyInfoBuilder.build(), senderUid);
			
	    	// 按照定义的数据结构，创建登录返回消息对象  
			JoinLobbyRsp.Builder joinLobbyRspBuilder = JoinLobbyRsp.newBuilder();
    		ImMsg.Builder imMsgBuilder = ImMsg.newBuilder();
            
    		joinLobbyRspBuilder.setResult(true);
    		joinLobbyRspBuilder.setDesctiption("加入大厅成功");
    		JoinLobbyRsp joinLobbyRsp = joinLobbyRspBuilder.build();
            
            imMsgBuilder.setMsg(Any.pack(joinLobbyRsp));
            imMsgBuilder.setId(imMsg.getId());
	        //发送反馈消息
	        currSession.sendMessage(imMsgBuilder.build());
	        
		}catch(Exception e) {
			log.error("加入大厅时发生异常, ", e);
		}
		
		
	}
	
	public void leaveLobby(ImMsg imMsg, IoSession currSession) {
		
		try {
			if(currSession.getUser() == null) {
				currSession.sendMessage(MessageBuilder.buildErrorResponse(imMsg, MessagingConst.RESPONSE_ERR_CODE_400, "用户未登录!"));
				return;
			}
			String sender_uid = currSession.getUser().getUid();
			
			
			LobbyInfo lobbyInfo = SessionManager.userId2Lobbies.get(sender_uid);
			if(lobbyInfo == null) {
				currSession.sendMessage(MessageBuilder.buildErrorResponse(imMsg, MessagingConst.RESPONSE_ERR_CODE_400, "User not in any lobby."));
				return;
			}
			
			LobbyRoomInfo lobbyRoomInfo = SessionManager.userId2LobbyRooms.get(sender_uid);
			if(lobbyRoomInfo != null) {//先退出房间
				lobbyRoomService.processLeaveRoom(currSession.getUser(), lobbyRoomInfo);
			}
			
			processExitLobby(sender_uid, lobbyInfo);
			
	    	// 按照定义的数据结构，创建登录返回消息对象  
			LeaveLobbyRsp.Builder leaveLobbyRspBuilder = LeaveLobbyRsp.newBuilder();
    		ImMsg.Builder imMsgBuilder = ImMsg.newBuilder();
            imMsgBuilder.setMsg(Any.pack(leaveLobbyRspBuilder.build()));
            imMsgBuilder.setId(imMsg.getId());
	        //发送反馈消息
	        currSession.sendMessage(imMsgBuilder.build());
	        
		}catch(Exception e) {
			log.error("Leave Lobby时发生异常, ", e);
		}
		
	}
	
	public void processExitLobby(String uid, LobbyInfo lobbyInfo) {
		Map<String, ChatUserInfo> lobbyUserMap = SessionManager.lobby2Users.get(lobbyInfo.getName());
		if(lobbyUserMap != null && lobbyUserMap.get(uid) != null) {
			//广播大厅信息刷新消息
			LobbyInfoRsp.Builder lobbyInfoRspBuilder = LobbyInfoRsp.newBuilder();
			lobbyInfoRspBuilder.addAllMRoomInlobby(MessageBuilder.buildRoomInfoListMsg(lobbyInfo.getRoomsInfo().values()));
			ImMsg.Builder imMsglobbyInfoBuilder = ImMsg.newBuilder();
            
			imMsglobbyInfoBuilder.setMsg(Any.pack(lobbyInfoRspBuilder.build()));
			//imMsglobbyInfoBuilder.setId(imMsg.getId());
			sessionManager.sendMessageToLobbyUsers(imMsglobbyInfoBuilder.build(), uid);
			
			lobbyUserMap.remove(uid);
			if(lobbyUserMap== null || lobbyUserMap.isEmpty()) {
				//销魂大厅数据
				SessionManager.lobby2Users.remove(lobbyInfo.getName());
			}
			
		}
		
		SessionManager.userId2Lobbies.remove(uid);
	}
	
	
	public void requestLobbyInfo(ImMsg imMsg, IoSession currSession) {
		
		try {
			if(currSession.getUser() == null) {
				currSession.sendMessage(MessageBuilder.buildErrorResponse(imMsg, MessagingConst.RESPONSE_ERR_CODE_400, "用户未登录!"));
				return;
			}
			String sender_uid = currSession.getUser().getUid();
			
			LobbyInfo lobbyInfo = SessionManager.userId2Lobbies.get(sender_uid);
			if(lobbyInfo == null) {
				currSession.sendMessage(MessageBuilder.buildErrorResponse(imMsg, MessagingConst.RESPONSE_ERR_CODE_400, "User not in any lobby."));
				return;
			}
			
			
	    	// 按照定义的数据结构，创建登录返回消息对象  
			LobbyInfoRsp.Builder lobbyInfoRspBuilder = LobbyInfoRsp.newBuilder();
			lobbyInfoRspBuilder.addAllMRoomInlobby(MessageBuilder.buildRoomInfoListMsg(lobbyInfo.getRoomsInfo().values()));
			ImMsg.Builder imMsglobbyInfoBuilder = ImMsg.newBuilder();
            
			imMsglobbyInfoBuilder.setMsg(Any.pack(lobbyInfoRspBuilder.build()));
	        //发送反馈消息
	        currSession.sendMessage(imMsglobbyInfoBuilder.build());
	        
		}catch(Exception e) {
			log.error("查询大厅信息时发生异常, ", e);
		}
		
	}
	
	
}
